#include <iostream>
#include <algorithm>

using namespace std;
int p[11] = {};
int a, b;

void swap(int &a, int &b) {
    int temp = a;
    a = b;
    b = temp;
}

bool cmp(int x, int y) {
    return x > y;
}

void solve() {
    cin >> a >> b;
    int ia = 0;
    while (a != 0) {
        p[++ia] = a % 10;
        a /= 10;
    }
    for (int i = 1; i <= ia / 2; i++) {
        swap(p[i], p[ia - i + 1]);
    }
    sort(p + 1, p + ia + 1, cmp);
    do {
        int x = 0;
        for (int i = 1; i <= ia; i++) {
            x = x * 10 + p[i];
        }
        if (x <= b) {
            cout << x;
            return;
        }
    } while (prev_permutation(p + 1, p + ia + 1));
    cout << "-1";
}

int main() {
    solve();
}